package lily.phs.mental;

import java.util.ArrayList;

import lily.phs.child.ImageList;
import lily.phs.database.Constants;
import lily.phs.pregnance.PregnantList;
import lily.phs.pregnance.PregnantScrollActivity;
import lily.phs.pregnance.PregnantList.myThread;
import lily.phs.urh.R;
import lily.ui.bookshelf.CaseLevelView;
import lily.ui.bookshelf.ProfileView;
import lily.ui.bookshelf.WindowSizeUtil;
import lily.ui.control.SearchPopupWindow;
import lily.ui.panel.Panel;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * 精神病患者的档案列表
 * @author heck
 *
 */
public class MentalerList extends Activity implements Constants, OnClickListener {

	private View view;
	private ArrayList<CaseLevelView> AllLevels;
	private LinearLayout ll_Content;
	private int ProfilesSUM;//档案总数
	private int ProfilesInOneLevel;//每层最多可放置的档案数
	private String[] allProfiles;
	private ProgressDialog mpDialog;
	private int idList[];
	private SearchPopupWindow sPopupWindow;
	private Button leftBtn,rightBtn2,rightBtn;
	private TextView tvTitle;
	private Panel panel;
	
	private final Handler handler = new Handler(Looper.getMainLooper()) {
    	public void handleMessage(Message msg) { // 处理Message，更新ListView 
    		if(msg.what==1){
    			for(int i=0;i<AllLevels.size();i++){
    				AllLevels.get(i).removeAllViews();
    			}
    			ProfilesInOneLevel = getProfilesInOneLevel();
    			if(ProfilesInOneLevel<1){
    				ProfilesInOneLevel=4;
    			}
    			for(int i=0;i<allProfiles.length;i++){
    	            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
    	            System.out.println("selectedLevel="+selectedLevel);
    	            addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
    	        }
    			mpDialog.cancel();
    		}
    	} 
    }; 
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        
        final LayoutInflater factory = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = factory.inflate(R.layout.profilecase, null);
        tvTitle = (TextView)view.findViewById(R.id.title);
        tvTitle.setText("精神疾病患者管理");
        
        panel = (Panel)view.findViewById(R.id.bottompanel);
        
        ll_Content = (LinearLayout)view.findViewById(R.id.shelves_content);
        AllLevels = new ArrayList<CaseLevelView>();
        
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();
        addNewLevel();//初始时加入6层以填充界面
        
        mpDialog = new ProgressDialog(MentalerList.this);  
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
		mpDialog.setMessage("正在加载...");  
		mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
		mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
		mpDialog.show();
		new myThread(handler,"",2).start();
        
		GridView grid = (GridView)this.findViewById(R.id.bottomgrid);
		String[] menus = new String[]{"刷新","查询"};
		int[] images = new int[]{R.drawable.add_files,R.drawable.search_file};
		ImageList adapter = new ImageList(this,images,menus);
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int item,
					long arg3) {
				// TODO Auto-generated method stub
				panel.setOpen(false, false);
				
				switch(item){
				case 0:{
					mpDialog = new ProgressDialog(MentalerList.this);  
					mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
					mpDialog.setMessage("正在加载...");  
					mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
					mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
					mpDialog.show();
					new myThread(handler,"",2).start();
					break;
				}
				case 1:{
					sPopupWindow = new SearchPopupWindow(getBaseContext());		
					sPopupWindow.showAtLocation(findViewById(R.id.title_left_btn), Gravity.CENTER, 0, 0);
					sPopupWindow.setAnimationStyle(R.anim.i_slide_in_left);
					final Button bt=sPopupWindow.getBt();
					final EditText et=sPopupWindow.getEt();
					bt.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							//searchContentView(et.getText().toString());
							mpDialog = new ProgressDialog(MentalerList.this);  
							mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
							mpDialog.setMessage("正在搜索...");  
							mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
							mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
							mpDialog.show();
							new myThread(handler,et.getText().toString(),1).start();
						}
						
					});
					break;
				}
				}
				
			}
			
		});
		
		leftBtn = (Button) findViewById(R.id.title_left_btn);
        rightBtn = (Button) findViewById(R.id.title_right_btn);
        rightBtn2 = (Button) findViewById(R.id.title_right_btn2);
        leftBtn.setText("后退");
        rightBtn.setVisibility(View.INVISIBLE);
        rightBtn2.setVisibility(View.INVISIBLE);
        leftBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
        	
        });
		
        
	}
	
	/**
	 * @return 每一层可放的档案数
	 */
    private int getProfilesInOneLevel() {
    	// TODO Auto-generated method stub
		
    	WindowSizeUtil util = new WindowSizeUtil(this);
		ProfileView newProfile = new ProfileView(this);
		return util.ScreenWidth/newProfile.FileWidth;
		
    }
    
    /**
	 * 添加一个新的健康档案
	 * @param level 放置的层
	 * @param ProfileName 档案名
	 * @param ProfileId 档案ID
	 */
	private void addNewProfileInLevel(int level,String ProfileName,int ProfileId) {
		// TODO Auto-generated method stub
		ProfileView newProfile = new ProfileView(this);
		String s=""+ProfileId;
		newProfile.button.setText(ProfileName);//档案名称
		newProfile.button.setId(ProfileId);//档案编号
		newProfile.button.setContentDescription(s);
		System.out.println("addFile:"+ProfileName+ProfileId);
		newProfile.button.setOnClickListener(this);
		
		if(level>=AllLevels.size()){
			addNewLevel();
		}
		AllLevels.get(level).addView(
				newProfile,//,newProfile.FileWidth,newProfile.FileHeight);
				MeasureSpec.makeMeasureSpec(newProfile.FileWidth, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(newProfile.FileHeight, MeasureSpec.EXACTLY));

		System.out.println("addFile:"+newProfile.FileWidth+","+newProfile.FileHeight);
		setContentView(view);
	}
	
	/**
	 * 添加一个新的层
	 */
	private void addNewLevel() {
		// TODO Auto-generated method stub
		CaseLevelView newcaseLevelView = new CaseLevelView(this);
		AllLevels.add(newcaseLevelView);
		ll_Content.addView(
				newcaseLevelView,newcaseLevelView.LevelWidth,newcaseLevelView.LevelHeight);//
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY),
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelHeight, MeasureSpec.EXACTLY));
//		Log.i(TAG, ""+MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY));
		System.out.println("addLevel:"+newcaseLevelView.LevelWidth+","+newcaseLevelView.LevelHeight);
		setContentView(view);
	}
	
	/**
	 * 初始化整个界面
	 */
	protected void initContentView() {
		// TODO Auto-generated method stub
		//取出该用户的全部档案
		//孕产妇管理的测试数据
		
		Cursor cursor = this.managedQuery(CONTENT_URI_TB16, null , null/*USPE_ID+"='"+userid+"'"*/, null, null);
		ProfilesSUM = cursor.getCount();
		ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	allProfiles[i] = "孕妇"+i;//cursor.getString(cursor.getColumnIndex(HETI_NAME));
        	
        	long ID = Long.parseLong(cursor.getString(cursor.getColumnIndex(FIPV_COLUMN1)));
            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
            System.out.println("selectedLevel="+selectedLevel);
            //addNewProfileInLevel(selectedLevel,allProfiles[i],ID);
        }
		
	}
	
	/**
	 * 刷新界面
	 * @param name
	 * @param state
	 */
	protected void searchContentView(String name,int state) {
		Cursor cursor;
		name.replace(" ", "");
		if(state==1){
		cursor = this.managedQuery(CONTENT_URI_VIEW4,null, 
				HETI_NAME+" LIKE '%"+name+"%'", null, null);
		}
		else {
			cursor = this.managedQuery(CONTENT_URI_VIEW4,null, 
					null, null, null);
		}
		ProfilesSUM = cursor.getCount();
		//ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        idList=new int[ProfilesSUM];
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	int ID = cursor.getInt(0);
        	idList[i]=cursor.getInt(0);
        	System.out.println("idList[]="+idList[i]);
        	allProfiles[i] =cursor.getString(1);
        }
	}
	
	public class myThread extends Thread{  
		private Handler handler;
		private String str;
		private int state;
		public myThread(Handler handler,String s,int state){
			this.handler=handler;
			this.str=s;
			this.state=state;
		}
		
		public void run(){  
	        try  
	        {   
	        	Looper.getMainLooper();
	        	sleep(200); 
	        	searchContentView(this.str,this.state);
	        	Message msg = handler.obtainMessage(); 
	        	msg.what=1;
	        	handler.sendMessage(msg); 
			}  
		    catch (Exception e)  
		    {  
		        e.printStackTrace();  
		    }  
		}  
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent editprofile = new Intent();
		Bundle bd = new Bundle();
		bd.putInt("Profile_id", v.getId());//待编辑档案的ID
		bd.putInt("father", MODULE_FATHER);
		bd.putInt("call", MODULE_LIST);
		editprofile.putExtras(bd);
		editprofile.setClass(MentalerList.this, MentalerDetails.class);
		startActivity(editprofile);
		overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
	}

}
